import { RouteRecordRaw } from 'vue-router'
import { ROUTER_NAME } from '@/constant'
import microApp from '@micro-zoe/micro-app'

const modules = import.meta.globEager('./modules/**/*.ts')

const routeModuleList: RouteRecordRaw[] = []

// 判断是否是子应用
const microAppData = window.eventCenterForViteApp?.getData()
Object.keys(modules).forEach(key => {
    const mod = modules[key].default || {}
    const modList = Array.isArray(mod) ? [...mod] : [mod]
    if (microAppData) {
        // 子应用不要外层结构
        const [children] = modList.map(item => item.children)
        // 兼容创建的应用中，路由没有children的情况
        if (children) {
            // 微应用前缀支持自定义传入
            const basePath = microAppData.baseroute || '/allin-app'

            const setBaseForPath = childrenMap => {
                childrenMap.forEach((item: any) => {
                    item.path = `${basePath}${item.path}`
                    if (item.children && item.children.length > 0) {
                        setBaseForPath(item.children)
                    }
                })
            }
            setBaseForPath(children)

            routeModuleList.push(...children)
        }
    } else {
        routeModuleList.push(...modList)
    }
})

/**
 * 动态获取路由信息，启动vite子应用
 * 支持同时配了多个子应用
 */
const viteMap: any = {}
const handleMicroAppPath = (item: any) => {
    if (item.path) {
        if (item.path.indexOf('/allin-app/') > -1) {
            const childPackageName = item.path.split('/allin-app/').pop().split('/').shift()
            if (childPackageName !== '' && viteMap[childPackageName] === undefined) {
                viteMap[childPackageName] = [
                    {
                        loader(code: string) {
                            const reg = new RegExp(`(from|import)([\\(\\s]*[\\(]?['"])(\/${childPackageName}\/)`, 'g')
                            // 本地开发调试时， 将 location.origin替换成本地的域名+端口
                            code = code.replace(reg, all =>
                                all.replace(`/${childPackageName}/`, `${location.origin}/${childPackageName}/`)
                            )
                            return code
                        }
                    }
                ]
            }
        }
    }
    if (item.hasOwnProperty('children')) {
        ;(item.children ?? []).forEach((child: any) => {
            handleMicroAppPath(child)
        })
    }
}
routeModuleList.forEach(item => handleMicroAppPath(item))
microApp.start({
    plugins: {
        modules: viteMap
    }
})

export const NOT_FOUND_PAGE: RouteRecordRaw = {
    name: ROUTER_NAME.PAGE_NOT_FOUND,
    // 匹配全部其他内容
    path: import.meta.env.VITE_PUBLIC_PATH + '/:pathMatch(.*)*',
    component: () => import('@/views/system/PageNotFound.vue'),
    meta: {
        hideMenu: true,
        hideBreadcrumb: true,
        title: '404'
    }
}

export const NO_ACCESS_PAGE: RouteRecordRaw = {
    name: ROUTER_NAME.PAGE_NO_ACCESS,
    // 匹配全部其他内容
    path: import.meta.env.VITE_PUBLIC_PATH + '/403',
    component: () => import('@/views/system/PageNoAccess.vue'),
    meta: {
        hideMenu: true,
        hideBreadcrumb: true,
        title: '403'
    }
}

export const LOGIN_PAGE: RouteRecordRaw = {
    name: ROUTER_NAME.PAGE_LOGIN,
    // 匹配全部其他内容
    path: import.meta.env.VITE_PUBLIC_PATH + '/login',
    component: () => import('@/views/system/login/Login.vue'),
    meta: {
        hideMenu: true,
        hideBreadcrumb: true,
        title: 'Login'
    }
}

export const ROOT_PAGE: RouteRecordRaw = {
    path: '/ROOT_PATH',
    name: ROUTER_NAME.PAGE_ROOT,
    redirect: import.meta.env.VITE_PUBLIC_PATH + '/',
    meta: {
        title: 'Root',
        hideMenu: true,
        hideBreadcrumb: true
    }
}

export const asyncRoutes = [...routeModuleList, NOT_FOUND_PAGE, NO_ACCESS_PAGE]
